#include <cstring>
#include <iostream>
#include <unistd.h>

#include "../logs/bin.hpp"

/*扩展一个以时间作为入职文件滚动切换类型的日志落地模块
    1.以当前时间，取模时间段大小，可以得到当前时间段是第几个时间段
    2.每次以当前系统时间取模，判断与当前文件的时间段是否一致，不一致则代表不是同一个时间段
*/

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public bin::LogSink
{
public:
    RollByTimeSink(const std::string &basename, TimeGap gap_type)
        : _basename(basename), _name_count(0)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? bin::util::Date::now() : bin::util::Date::now() % _gap_size; // 获取当前时间段
        std::string pathname = createNewFile();
        // 创建文件目录
        bin::util::File::createDirectory(bin::util::File::path(pathname));
        // 创建并打开日志文件
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    // 在写入前判断时间段，不符合要切换文件
    void log(const char *data, size_t len)
    {
        time_t cur = _gap_size == 1 ? bin::util::Date::now() : bin::util::Date::now() % _gap_size; // 获取当前时间段
        if (cur != _cur_gap)
        {
            _ofs.close(); // 关闭原来已经打开的文件
            std::string pathname = createNewFile();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = cur;
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile() // 生成文件名
    {
        // 获取系统时间，以时间构建文件名扩展名
        time_t t = bin::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        filename << "-";
        filename << _name_count++;
        return filename.str();
    }

private:
    size_t _name_count; // 名称计数器，防止同一时间生成了多个文件，这些文件名字都相同
    // 基础文件名 + 扩展文件名 生成最终文件名
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 记录当前是第几个时间段
    size_t _gap_size; // 记录时间段大小
};

void test_log(const std::string& name)
{
    bin::Logger::ptr logger = bin::LoggerManager::getInstance().getLogger(name);

    logger->info("测试开始");

    logger->debug("测试日志-");
    logger->info("测试日志-");
    logger->warn("测试日志-");
    logger->error("测试日志-");
    logger->fatal("测试日志-");

    logger->info("测试结束");
}



// void test_log()
// {
//     //bin::Logger::ptr logger = bin::LoggerManager::getInstance().getLogger("async_logger");
//     DEBUG("%s", "测试日志-");
//     INFO("测试日志-");
//     WARN("测试日志-");
//     ERROR("测试日志-");
//     FATAL("测试日志-");

//     size_t count = 0;
//     while (count < 5000)
//     {
//         // std::string tmp = str + std::to_string(count++);
//         FATAL("测试日志-%d", count++);
//     }
// }





void test_log()
{
    INFO("测试开始");

    DEBUG("测试日志-");
    INFO("测试日志-");
    WARN("测试日志-");
    ERROR("测试日志-");
    FATAL("测试日志-");

    INFO("测试结束");
}


int main()
{

    std::unique_ptr<bin::LoggerBuilder> builder(new bin::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(bin::LogLevel::value::WARN);
    builder->buildFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(bin::LoggerType::LOGGER_ASYNC);
    // builder->buildEnableUnSafeAsync();
    builder->buildSink<bin::StdoutSink>();
    builder->buildSink<bin::FileSink>("./logfile/test.log");
    builder->buildSink<bin::RollBySizeSink>("./logfile/rool-", 1024*1024);
    builder->build();

    test_log();
    
    test_log("async_logger");
    
    
    // //读取文件数据，一点一点写入缓冲区，最终将缓冲区数据写入文件，判断是否一致
    // std::ifstream ifs("./logfile/test.log", std::ios::binary);
    // if(ifs.is_open() == false)
    //     return -1;
    // ifs.seekg(0, std::ios::end);//读写位置跳转到文件末尾
    // size_t fsize = ifs.tellg();//获取当前读写位置相对于起始位置的偏移量
    // ifs.seekg(0, std::ios::beg);//重新读写位置跳转到文件起始位置
    // std::string body;
    // body.resize(fsize);
    // ifs.read(&body[0], fsize);
    // if(ifs.good() == false)
    // {
    //     std::cout << "read error " << strerror(errno) << " : " << errno << std::endl;
    //     return -1;
    // }
    // ifs.close();

    // std::cout << fsize << std::endl;
    // bin::Buffer buffer;
    // for(int i = 0; i < body.size(); i++)
    // {
    //     buffer.push(&body[i], 1);
    // }
    // std::cout << buffer.readAbleSize() << std::endl;

    // std::ofstream ofs("./logfile/tmp.log", std::ios::binary);
    // // ofs.write(buffer.begin(), buffer.readAbleSize());
    // int sum = buffer.readAbleSize();
    // for(int i = 0; i < sum; i++)
    // {
    //     ofs.write(buffer.begin(), 1);
    //     if(!ofs.good())
    //     {
    //         std::cout << "write error\n";
    //         return -1;
    //     }
    //     buffer.moveReader(1);
    // }

    // ofs.close();

    // std::unique_ptr<bin::LoggerBuilder> builder(new bin::LocalLoggerBuilder());
    // builder->buildLoggerName("async_logger");
    // builder->buildLoggerLevel(bin::LogLevel::value::WARN);
    // builder->buildFormatter("[%c]%m%n");
    // builder->buildLoggerType(bin::LoggerType::LOGGER_ASYNC);
    // // builder->buildEnableUnSafeAsync();
    // builder->buildSink<bin::StdoutSink>();
    // builder->buildSink<bin::FileSink>("./logfile/test.log");
    // builder->buildSink<bin::RollBySizeSink>("./logfile/rool-", 1024 * 1024);
    // bin::Logger::ptr logger = builder->build();

    // size_t cursize = 0;
    // size_t count = 0;
    // std::string str = "测试日志-";
    // logger->debug(__FILE__, __LINE__, "测试日志-");
    // logger->info(__FILE__, __LINE__, "测试日志-");
    // logger->warn(__FILE__, __LINE__, "测试日志-");
    // logger->error(__FILE__, __LINE__, "测试日志-");
    // logger->fatal(__FILE__, __LINE__, "测试日志-");
    // while (count < 5000)
    // {
    //     // std::string tmp = str + std::to_string(count++);
    //     logger->fatal(__FILE__, __LINE__, "测试日志-%d", count++);
    // }

    // std::string logger_name = "sync_logger";
    // bin::LogLevel::value limit = bin::LogLevel::value::WARN;
    // bin::Formatter::ptr fmt(new bin::Formatter);
    // bin::LogSink::ptr stdout_lsp = bin::SinkFactory::create<bin::StdoutSink>();
    // bin::LogSink::ptr file_lsp = bin::SinkFactory::create<bin::FileSink>("./logfile/test.log");
    // bin::LogSink::ptr roll_lsp = bin::SinkFactory::create<bin::RollBySizeSink>("./logfile/rool-", 1024 * 1024);
    // std::vector<bin::LogSink::ptr> sinks = {stdout_lsp, file_lsp, roll_lsp};
    // bin::Logger::ptr logger(new bin::SyncLogger(logger_name, limit, fmt, sinks));

    // bin::LogMsg msg(bin::LogLevel::value::INFO, 53, "main.c", "root", "格式化功能测试");
    // bin::Formatter fmt;
    // std::string str = fmt.format(msg);

    // bin::LogSink::ptr stdout_lsp = bin::SinkFactory::create<bin::StdoutSink>();
    // bin::LogSink::ptr file_lsp = bin::SinkFactory::create<bin::FileSink>("./logfile/test.log");
    // bin::LogSink::ptr roll_lsp = bin::SinkFactory::create<bin::RollBySizeSink>("./logfile/rool-", 1024*1024);
    // bin::LogSink::ptr time_lsp = bin::SinkFactory::create<RollByTimeSink>("./logfile/rool-", TimeGap::GAP_SECOND);
    // time_t old = bin::util::Date::now();
    // while(bin::util::Date::now() < old + 5)
    // {
    //     time_lsp->log(str.c_str(), str.size());
    // }

    // stdout_lsp->log(str.c_str(), str.size());
    // file_lsp->log(str.c_str(), str.size());
    // size_t cursize = 0;
    // size_t count = 0;
    // while(cursize < 1024*1024*10)
    // {
    //     std::string tmp = str + std::to_string(count++);
    //     roll_lsp->log(tmp.c_str(), str.size());
    //     cursize += tmp.size();
    // }

    // std::cout << bin::LogLevel::toString(bin::LogLevel::value::DEBUG) << std::endl;
    // std::cout << bin::LogLevel::toString(bin::LogLevel::value::INFO) << std::endl;
    // std::cout << bin::LogLevel::toString(bin::LogLevel::value::WARN) << std::endl;
    // std::cout << bin::LogLevel::toString(bin::LogLevel::value::ERROR) << std::endl;

    // std::cout << bin::util::Date::now() << std::endl;

    // std::string pathname = "./abc/bcd/a.txt";

    // bin::util::File::createDirectory(bin::util::File::path(pathname));
    return 0;
}